package com.oa.erp.ass.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.err.BizException;
import com.mdp.core.service.BaseService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.oa.erp.ass.entity.AssetInventoryTask;
import com.oa.erp.ass.entity.AssetInventoryTaskDetail;
import com.oa.erp.ass.enums.TaskDetailEnum;
import com.oa.erp.ass.enums.TaskEnum;
import com.oa.erp.ass.mapper.AssetInventoryTaskMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@Service
public class AssetInventoryTaskService extends BaseService<AssetInventoryTaskMapper, AssetInventoryTask> {
    static Logger logger = LoggerFactory.getLogger(AssetInventoryTaskService.class);

    @Autowired
    private AssetInventoryTaskUserService assetInventoryTaskUserService;

    @Autowired
    private AssetInventoryTaskDetailService assetInventoryTaskDetailService;

    @Autowired
    private AssetCardService assetCardService;

    /**
     * 自定义查询，支持多表关联
     *
     * @param page 分页条件
     * @param ew   一定要，并且必须加@Param("ew")注解
     * @param ext  如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
     * @return
     */
    public List<Map<String, Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String, Object> ext) {
        return baseMapper.selectListMapByWhere(page, ew, ext);
    }


    /**
     * 批量删除数据
     *
     * @param assetInventoryTasks
     */
    @Transactional
    public void batchDeleteAssetInventoryTask(List<AssetInventoryTask> assetInventoryTasks) {
        for (AssetInventoryTask assetInventoryTask : assetInventoryTasks) {
//            this.deleteAssetInventoryTask(assetInventoryTask);
            this.deleteByWhere(assetInventoryTask);
        }
    }

    /**
     * 获取盘点任务的明细卡片信息
     *
     * @param assetInventoryTaskMap
     * @return
     */
    public Map<String, Object> getTaskDetail(IPage page, QueryWrapper ew, Map<String, Object> assetInventoryTaskMap) {

        Map<String, Object> m = new HashMap<>();

        User user = LoginUtils.getCurrentUserInfo();
        //当前用户Id
        String currentUserId = user.getUserid();

        AssetInventoryTask assetInventoryTask = new AssetInventoryTask();
        assetInventoryTask.setTaskId(assetInventoryTaskMap.get("taskId").toString());

        //1.根据任务Id查询盘点任务
        AssetInventoryTask taskResult = this.selectOneObject(assetInventoryTask);

        //当前分配用户类型
        String allocationType = taskResult.getAllocationType();

        //2.查询关联的明细
//        PageUtils.startPage(assetInventoryTaskMap);

        if (!StringUtils.isEmpty(assetInventoryTaskMap.get("detailStatusArr"))) {
            assetInventoryTaskMap.put("detailStatusArr", assetInventoryTaskMap.get("detailStatusArr").toString().split(","));
        }
        List<Map<String, Object>> detailResult = assetInventoryTaskDetailService.selectTaskDetailAndCardMsg(assetInventoryTaskMap);
//        PageUtils.responePage(m, detailResult);

        //3.查询用权限使用的用户
        List<Map<String, Object>> userResult = assetInventoryTaskUserService.selectListMapByWhere(page, ew, assetInventoryTaskMap);

        //4.权限控制
        for (Map<String, Object> detail : detailResult) {

            //1.只能责任人操作
            if (allocationType.equals(TaskEnum.ALLOCATION_LIABLE.getStatus())) {
                //责任人
                if (currentUserId.equals(detail.get("personLiableUserid"))) {
                    detail.put("isCanOper", true);
                } else {
                    detail.put("isCanOper", false);
                }
            }

            //2.只能责任人操作和选择中的用户操作
            if (allocationType.equals(TaskEnum.ALLOCATION_LIABLE_AND_SELECTUSER.getStatus())) {

                if (currentUserId.equals(detail.get("personLiableUserid"))) {
                    detail.put("isCanOper", true);
                } else {
                    detail.put("isCanOper", false);
                }

                userResult.forEach(u -> {
                    if (currentUserId.equals(u.get("inventoryUserid").toString())) {
                        detail.put("isCanOper", true);
                    }
                });
            }

            //3.只能选择中的用户操作
            if (allocationType.equals(TaskEnum.ALLOCATION_SELECTUSER.getStatus())) {
                userResult.forEach(u -> {
                    if (currentUserId.equals(u.get("inventoryUserid").toString())) {
                        detail.put("isCanOper", true);
                    } else {
                        detail.put("isCanOper", false);
                    }
                });
            }
        }

        m.put("data", detailResult);
        return m;
    }


    /**
     * 获取我的待盘点对象
     *
     * @param assetInventoryTaskMap
     * @return
     */
    public Map<String, Object> getMyTaskDetail(IPage page, QueryWrapper ew, Map<String, Object> assetInventoryTaskMap) {
        Map<String, Object> m = new HashMap<>();

        User user = LoginUtils.getCurrentUserInfo();
        String currentUserId = user.getUserid();

        AssetInventoryTask assetInventoryTask = new AssetInventoryTask();
        assetInventoryTask.setTaskId(assetInventoryTaskMap.get("taskId").toString());

        //1.根据任务Id查询盘点任务
        AssetInventoryTask taskResult = this.selectOneObject(assetInventoryTask);

        //当前分配用户类型
        String allocationType = taskResult.getAllocationType();

        //查询当前可操作的用户
        //3.查询用权限使用的用户
        List<Map<String, Object>> userResult = assetInventoryTaskUserService.selectListMapByWhere(page, ew, assetInventoryTaskMap);

        //1.只能责任人操作
        if (allocationType.equals(TaskEnum.ALLOCATION_LIABLE.getStatus())) {
            //查询数据
            //2.查询关联的明细
//            PageUtils.startPage(assetInventoryTaskMap);
            if (!StringUtils.isEmpty(assetInventoryTaskMap.get("detailStatusArr"))) {
                assetInventoryTaskMap.put("detailStatusArr", assetInventoryTaskMap.get("detailStatusArr").toString().split(","));
            }
            assetInventoryTaskMap.put("operId", currentUserId);
            List<Map<String, Object>> detailResult = assetInventoryTaskDetailService.selectTaskDetailAndCardMsg(assetInventoryTaskMap);
            detailResult.forEach(d -> {
                d.put("isCanOper", true);
            });
//            PageUtils.responePage(m, detailResult);
            m.put("data", detailResult);
        } else {
            Boolean flag = false;

            //当前用户是否存在可操作人中
            for (Map<String, Object> stringObjectMap : userResult) {
                if (currentUserId.equals(stringObjectMap.get("inventoryUserid").toString())) {
                    flag = true;
                }
            }

            if (flag) {
//                PageUtils.startPage(assetInventoryTaskMap);
                if (!StringUtils.isEmpty(assetInventoryTaskMap.get("detailStatusArr"))) {
                    assetInventoryTaskMap.put("detailStatusArr", assetInventoryTaskMap.get("detailStatusArr").toString().split(","));
                }
                List<Map<String, Object>> detailResult = assetInventoryTaskDetailService.selectTaskDetailAndCardMsg(assetInventoryTaskMap);
                detailResult.forEach(d -> {
                    d.put("isCanOper", true);
                });
//                PageUtils.responePage(m, detailResult);
                m.put("data", detailResult);
            }

        }
        return m;
    }


    /**
     * 更新资产卡片是否正在盘点状态
     */
    public void updateCardInventoryStatus(List<String> cardIds, String isInventoryIng) {
        Map<String, Object> params = new HashMap<>();
        params.put("cardIds", cardIds);
        params.put("status", isInventoryIng);
        //1.修改资产卡片状态为未在盘点。
        assetCardService.batchUpdateAssetCardInventoryStatus(params);
    }


    @Transactional
    public void updateTaskDetailStatus(List<String> cardIds, String taskId, String mngId, String detailStatus) {
        //修改盘点任务状态。
        Map<String, Object> params2 = new HashMap<>();
        params2.put("cardIds", cardIds);
        params2.put("taskId", taskId);
        params2.put("mngId", mngId);
        params2.put("status", detailStatus);
        //修改资产卡片状态为未在盘点。
        assetInventoryTaskDetailService.batchUpdateTaskDetailStatus(params2);
    }

    /**
     * 获取当前任务能操作的人员
     *
     * @param assetInventoryTask
     * @return
     */
    public List<Map<String, Object>> getCanOperTaskUser(IPage page, QueryWrapper ew, Map<String, Object> assetInventoryTask) {
        return assetInventoryTaskUserService.selectListMapByWhere(page, ew, assetInventoryTask);
    }


    //完成资产盘点
    @Transactional
    public void finishInventory(Map<String, Object> assetMng) {
        //1.修改资产task_status为完成
//        AssetInventoryTask assetInventoryTask = (AssetInventoryTask) this.selectOneObject(assetMng);
        AssetInventoryTask assetInventoryTask = super.selectOneById(assetMng);
        if (StringUtils.isEmpty(assetInventoryTask)) {
            throw new BizException("该记录不存在");
        }
        assetInventoryTask.setTaskStatus(TaskEnum.OVER.getStatus());
        this.updateByPk(assetInventoryTask);

        //2.查询出当前资产关联卡片中未完成数据将其资产状态修改为未盘点
        assetMng.put("detailStatus", TaskDetailEnum.INVENTORY_STAY.getStatus());

        AssetInventoryTaskDetail assetInventoryTaskDetail = new AssetInventoryTaskDetail();
        assetInventoryTaskDetail.setTaskId(assetInventoryTask.getTaskId());
        assetInventoryTaskDetail.setDetailStatus(TaskDetailEnum.INVENTORY_STAY.getStatus());

        List<AssetInventoryTaskDetail> assetInventoryTaskDetails = assetInventoryTaskDetailService.selectListByWhere(assetInventoryTaskDetail);

        if (!CollectionUtils.isEmpty(assetInventoryTaskDetails)) {

            List<String> cardIds = new ArrayList<>();

            //1.修改状态
            for (AssetInventoryTaskDetail inventoryTaskDetail : assetInventoryTaskDetails) {
                cardIds.add(inventoryTaskDetail.getCardId());
                inventoryTaskDetail.setDetailStatus(TaskDetailEnum.INVENTORY_NOT.getStatus());
            }
            assetInventoryTaskDetailService.batchUpdate(assetInventoryTaskDetails);

            //2.修改资产卡片正在盘点状态为未盘点
            Map<String, Object> params = new HashMap<>();
            params.put("cardIds", cardIds);
            params.put("status", 0);
            assetCardService.batchUpdateAssetCardInventoryStatus(params);
        }
    }

    //开启资产盘点
    public void beginInventory(Map<String, Object> assetMng) {
//        AssetInventoryTask assetInventoryTask = (AssetInventoryTask) this.selectOneObject(assetMng);
        AssetInventoryTask assetInventoryTask = this.selectOneById(assetMng);
        if (StringUtils.isEmpty(assetInventoryTask)) {
            throw new BizException("该记录不存在");
        }
        assetInventoryTask.setTaskStatus(TaskEnum.RUNNING.getStatus());
        this.updateByPk(assetInventoryTask);
    }
}

